'use client';
import { motion, AnimatePresence } from 'framer-motion';
import { usePathname } from 'next/navigation';
import { useContext, useEffect } from 'react';
import { LoadingContext } from './CustomLink';

interface RouteTransitionProps {
  children: React.ReactNode;
}

const RouteTransition = ({ children }: RouteTransitionProps) => {
  const pathname = usePathname();
  const loadingContext = useContext(LoadingContext);

  if (!loadingContext) {
    throw new Error('RouteTransition must be used within a LoadingProvider');
  }

  const { isLoading, setIsLoading } = loadingContext;

  // 当路径变化完成后，隐藏加载指示器
  useEffect(() => {
    if (isLoading) {
      // 设置一个定时器，确保加载指示器至少显示一段时间，提供更好的用户体验
      const timer = setTimeout(() => {
        setIsLoading(false);
      }, 300);

      return () => clearTimeout(timer);
    }
  }, [pathname, isLoading, setIsLoading]);

  return (
    <>
      {/* 加载指示器 */}
      <AnimatePresence>
        {isLoading && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="fixed inset-0 flex items-center justify-center z-50 bg-black bg-opacity-30"
          >
            <motion.div
              className="w-20 h-20 border-4 border-white border-t-transparent rounded-full"
              animate={{ rotate: 360 }}
              transition={{ repeat: Infinity, duration: 0.8, ease: "linear" }}
            />
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="mt-8 text-white font-semibold text-lg"
            >
              正在加载页面...
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 页面内容 */}
      <div key={pathname} className="w-full">
        {children}
      </div>
    </>
  );
};

export default RouteTransition;
